using System;
using System.Collections.Generic;
using System.Text;

using libsecondlife;
using libsecondlife.InventorySystem;

using Feathertail;

namespace NestBox.Inventory
{
    class rm : Feathertail.Command
    {
        FeathertailClient _Client;

        #region Command Members

        public void Setup(FeathertailClient Client)
        {
            _Client = Client;
        }

        public string HandleInput(string[] CmdLine)
        {
            if (CmdLine.Length < 2)
            {
                return GetHelpText();
            }

            string cmdLineCombined = NestBox.Inventory.Helpers.combineCmdArg(CmdLine);
            string targetDir;
            string targetFile;

            if( cmdLineCombined.Contains("/") )
            {
                targetDir = cmdLineCombined.Remove(cmdLineCombined.LastIndexOf("/"));
                targetFile = cmdLineCombined.Remove(0, cmdLineCombined.LastIndexOf("/") + 1);
            } else {
                targetFile = cmdLineCombined;
                targetDir = (string)_Client.FeathertailState[Helpers.CurrentDirectoryKey];
            }


            InventoryFolder iFolder = _Client.Inventory.getFolder(targetDir);
            if (iFolder == null)
            {
                return "Could not find directory: " + targetDir;
            }
            else
            {
                // Refresh folder
                iFolder.RequestDownloadContents(false, false, true).RequestComplete.WaitOne(3000, false);

                StringBuilder sbRtn = new StringBuilder();
                Queue<InventoryItem> Files2Delete = new Queue<InventoryItem>();
                foreach (InventoryBase ib in iFolder.GetContents())
                {
                    if (ib is InventoryItem)
                    {
                        InventoryItem iItem = (InventoryItem)ib;
                        if( iItem.Name.Equals(targetFile) || iItem.ItemID.Equals(targetFile) )
                        {
                            Files2Delete.Enqueue(iItem);
                        }
                    }
                }

                while (Files2Delete.Count > 0)
                {
                    InventoryItem iItem = Files2Delete.Dequeue();
                    sbRtn.AppendLine("Deleting " + iItem.Name + "[IID:" + iItem.ItemID + "]");
                    iItem.Delete();
                }

                return sbRtn.ToString();
            }
        }

        public string[] GetCommandStrings()
        {
            return new string[] { "rm", "del" };
        }

        public string GetSummaryText()
        {
            return "Remove a file from your inventory";
        }

        public string GetHelpText()
        {
            return "Usage: rm [file]";
        }

        #endregion
    }
}
